using System;
using System.ComponentModel;
using System.Diagnostics;
using Sedge.Core;
using Sedge.Core.Configuration;
using Sedge.Core.Execution;
using Sedge.Core.Utils;

namespace Sedge.UI.ViewModel
{
	public class CollectViewModel
	{
		#region Private Fields

		private readonly Suite _suite;
		private readonly Options _options;
		private readonly ReportGenerator _reportGenerator;
		private readonly BackgroundWorker _backgroundWorker;

		#endregion //Private Fields

		#region Public Fields

		public delegate void ProgressEventHandler(int step, string state);
		public event ProgressEventHandler ProgressEvent;

		public string Notes
		{
			get
			{
				return _options.Notes();
			}
		}

		public int StepsCount { get; set; }

		#endregion //Public Fields

		#region Constructors

		public CollectViewModel(Suite suite, Options options)
		{
			_suite = suite;
			_options = options;

			_reportGenerator = new ReportGenerator(suite);
			StepsCount = _reportGenerator.GetStepsCount();

			_backgroundWorker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true };
			_backgroundWorker.DoWork += BackgroundWorker_DoWork;
			_backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;
			_backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
		}

		#endregion //Constructors

		#region BackgroundWorker Events

		private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
		{
			if (ProgressEvent != null)
				ProgressEvent.Invoke(e.ProgressPercentage, (string)e.UserState);
		}

		private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
		{
			_reportGenerator.Run(_backgroundWorker);
		}

		private static void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			Services.ViewManager.UnlockView();
		}

		#endregion //BackgroundWorker Events

		#region Public Methods

		public void Start()
		{
			Services.ViewManager.LockView(_backgroundWorker.CancelAsync);
			_backgroundWorker.RunWorkerAsync();
		}

		public void ViewReport()
		{
			WebHelper.ShowHtml(Services.FileSystem.Path.Combine(_suite.WorkingFolder, "index.html"));
		}

		public void SendReport()
		{
			if (_suite.Transport != null)
			{
				_suite.Transport.Send(_suite, _suite.ZipFile);
			}
			else
			{
				try
				{
					Process.Start(_suite.WorkingFolder);
				}
				catch
				{
					// Nothing to do
				}
			}
		}

		public bool CanSendReport()
		{
			return (_suite.Transport == null) || 
				((_suite.Transport != null) && _suite.Transport.CanSend(_suite));
		}

		#endregion //Public Methods

	}
}